<?php

namespace app\admin\controller;

use app\common\model\Admin;
use think\Controller;
use think\facade\Config;
use think\facade\Request;
use app\admin\model\AdminUser as AdminUserModel;

class AdminUser extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkAdminToken::class'
    ];

    public function info()
    {
        $admin_id=Request::param('admin_id');
        $info=Admin::info($admin_id);
        $info->roles='admin';
        $this->result($info,200);
    }

    //添加用户的信息
    public function create()
    {
        $data=Request::only(['account','password','username','role','school_ids']);
        $data['work_status']=1;                             //0离职   1在职
        $data['avatar']=Config::get('logo');        //企业logo作为默认的员工头像
        $data['add_time']=time();
        $data['last_time']=0;

        //分配给他管理的学校
        $school_ids= json_decode($data['school_ids']);

        try{
            $res= AdminUserModel::create($data);
            $school_ids=  json_decode( Request::param('school_ids'));
        }catch (\Exception $e){
            return toResful(400,$e->getMessage(),'创建失败');
        }

        if($res){
            return toResful(200,$res,'创建成功');
        }else{
            return toResful(400,$res,'创建失败');
        }
    }

    //列表
    public function index(){
        $page=Request::param('page',1);
        $pageSize=Request::param('pageSize',20);
        $key=Request::param('key',null);

        //判断用户是不
        if($key!==null  && $key!==''){
            $list= AdminUserModel::where('account|username','like','%'.$key.'%')
                   ->page($page,$pageSize)->field(['password'],true)->select();
            $count= AdminUserModel::where('account|username','like','%'.$key.'%') ->count('id');
        }else{
            $list= AdminUserModel::page($page,$pageSize)->field(['password'],true)->select();
            $count= AdminUserModel::count('id');
        }

        $page_num=ceil($count/$pageSize);

        $data=[
            'list'=>$list,
            'page_num'=>$page_num,
            'page_current'=>$page,
         ];

        return toResful(200,$data,'');
    }

}
